<template>
  <custom-modal
    width="500px"
    :destroyOnClose="true"
    :maskClosable="false"
    @ok="handleOk"
    @cancel="handleCancel"
    :title="action === 'add' ? $t('addNewFlowConfig') : $t('editNewFlowConfig')"
    :visible="modalVisibal"
  >
    <a-form-model
      :model="form"
      v-bind="layout"
      class="formWrap"
      :rules="rules"
      :colon="false"
      ref="validateForm">
      <a-form-model-item :label="$t('business')" class="formItemForMargin" prop="business">
        <common-select
          :showSearch="true"
          :disabled="disableBusinessSelect"
          :default-value="businessSelection"
          :options="businessOptions"
          :allow-clear="false"
          @changeoption="handleBusinessSelection"
        ></common-select>
      </a-form-model-item>
      <a-form-model-item :label="$t('flow')" class="formItemForMargin" prop="flow">
        <common-select
          :showSearch="true"
          :options="flowOptions"
          :default-value="form.definitionId"
          :allow-clear="false"
          @changeoption="handleFlowSelection"
        ></common-select>
      </a-form-model-item>
      <a-form-model-item :label="$t('remark')" class="formItemForMargin">
        <custom-text-area @change="form.remark = $event" :val="form.remark" :max-len="200"></custom-text-area>
      </a-form-model-item>
    </a-form-model>
  </custom-modal>
</template>
<script>
import CustomModal from '@/components/CustomModal/index.vue'
import CommonSelect from '@/components/SelfComponents/CommonSelect.vue'
import CustomTextArea from '@/components/CustomTextArea/index.vue'

export default {
  name: 'AddConfigModal',
  components: {
    CustomModal,
    CommonSelect,
    CustomTextArea
  },
  props: {
    formData: {
      type: Object,
      default: () => {
        return {}
      }
    }
  },
  data () {
    const validateBusiness = (rule, value, callback) => {
      if (this.businessSelection) {
        // eslint-disable-next-line callback-return
        callback()
      } else {
        // eslint-disable-next-line callback-return
        callback(new Error(this.$t('pleaseSelect') + this.$t('business')))
      }
    }
    const validateFlow = (rule, value, callback) => {
      if (this.form.definitionId) {
        // eslint-disable-next-line callback-return
        callback()
      } else {
        // eslint-disable-next-line callback-return
        callback(new Error(this.$t('pleaseSelect') + this.$t('flow')))
      }
    }
    return {
      layout: {
        labelCol: { span: 6 },
        wrapperCol: { span: 14 }
      },
      modalVisibal: false,
      flowOptions: [],
      businessOptions: [],
      form: {
        businessName: '',
        businessCode: '',
        definitionId: '',
        remark: ''
      },
      businessSelection: '',
      disableBusinessSelect: false,
      action: 'add',
      rules: {
        business: [
          { required: true, validator: validateBusiness, trigger: 'change' }
        ],
        flow: [
          { required: true, validator: validateFlow, trigger: 'change' }
        ]
      }
    }
  },
  watch: {
    // 新增时监听业务的下拉选择，选择以后绑定业务名称和编码到新增表单
    businessSelection (val) {
      if (val) {
        this.businessOptions.forEach((element) => {
          if (element.id === val) {
            this.form.businessName = element.businessName
            this.form.businessCode = element.businessCode
          }
        })
      }
    }
  },
  methods: {
    // 业务下拉选择，因为自定义和绑定了名称，所以需要再次对字段校验取消表单项报错
    handleBusinessSelection ($event) {
      this.businessSelection = $event
      this.$refs.validateForm.validateField('business')
    },
    // 业务下拉选择，因为自定义和绑定了名称，所以需要再次对字段校验取消表单项报错
    handleFlowSelection ($event) {
      this.form.definitionId = $event
      this.$refs.validateForm.validateField('flow')
    },
    // 显示隐藏
    switchVisible (val, type, data) {
      if (val === true) {
        // 当打开对话框操作为新增时，获取两个下拉框选项
        if (type === 'add') {
          this.action = 'add'
          this.disableBusinessSelect = false
          const vm = this
          this.$api
            .getBusinessSelection()
            .then((res) => {
              if (res.data.data.length > 0) {
                vm.businessOptions = res.data.data.map((item) => {
                  return {
                    name: item.businessName + '[' + item.businessCode + ']',
                    id: item.businessCode,
                    value: item.businessCode,
                    businessName: item.businessName,
                    businessCode: item.businessCode
                  }
                })
                console.log(vm.businessOptions, 'businessOptions')
              } else {
                vm.businessOptions = []
              }
            })
          this.$api
            .getFlowSelection()
            .then((res) => {
              if (res.data.data.length > 0) {
                vm.flowOptions = res.data.data.map((item) => {
                  return {
                    name: item.definitionName + '[' + item.definitionCode + ']',
                    id: item.definitionId,
                    value: item.definitionId
                  }
                })
              } else {
                vm.flowOptions = []
              }
            })
        } else if (type === 'edit') {
          // 当打开对话框操作为编辑时，将数据直接赋值，禁用业务下拉，获取流程下拉框选项
          this.action = 'edit'
          this.disableBusinessSelect = true
          this.businessOptions = []
          this.businessOptions.push({
            name: data.businessName + '[' + data.businessCode + ']',
            id: data.businessCode,
            value: data.businessCode,
            businessName: data.businessName,
            businessCode: data.businessCode
          })
          this.businessSelection = data.businessCode
          this.form.id = data.id
          this.form.remark = data.remark
          this.form.businessName = data.businessName
          this.form.businessCode = data.businessCode
          const vm = this
          this.$api.getFlowSelection().then((res) => {
            if (res.data.data.length > 0) {
              vm.flowOptions = res.data.data.map((item) => {
                if (item.definitionId === data.definitionId) {
                  vm.form.definitionId = item.definitionId
                }
                return {
                  name: item.definitionName + '[' + item.definitionCode + ']',
                  id: item.definitionId,
                  value: item.definitionId
                }
              })
            } else {
              vm.flowOptions = []
            }
          })
        }
      }
      this.modalVisibal = val
    },
    // 对话框点击保存
    handleOk () {
      if (this.action === 'add') {
        const vm = this
        this.$refs.validateForm.validate((res) => {
          if (res) {
            vm.$api
              .addFlowConfig(vm.form)
              .finally(() => {
                vm.modalVisibal = false
                vm.resetData()
                vm.$emit('addOrEditDone', true)
              })
          }
        })
      } else if (this.action === 'edit') {
        this.$api
          .editFlowConfig(this.form)
          .finally(() => {
            this.modalVisibal = false
            this.resetData()
            this.$emit('addOrEditDone', true)
          })
      }
    },
    // 对话框点击取消
    handleCancel () {
      this.resetData()
      this.modalVisibal = false
    },
    // 手动重置数据
    resetData () {
      this.businessSelection = ''
      this.form.remark = ''
      this.form.businessName = ''
      this.form.businessCode = ''
      this.form.definitionId = ''
      delete this.form.id
    }
  }
}
</script>
<style lang="less" scoped>
.formWrap {
  margin-top: 20px;
  margin-bottom: 60px;
  .formItemForMargin {
    margin-bottom: 40px;
  }
}
</style>
